package com.common.base.http.exceptions

import com.common.base.http.main.CODE_INTERRUPTED_IO
import com.common.base.http.main.CODE_NO_HTTP
import com.common.base.http.main.CODE_NO_NETWORK
import com.common.base.http.main.CODE_TOKEN_INVALID
import com.common.base.http.main.CODE_UNKNOWN
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.UnknownHostException


data class CloudException(
        var code: Int? = -1,
        override var message: String? = "",
        var throwable: Throwable? = null
) : Exception(message, throwable) {
    companion object {
        fun accept(throwable: Throwable): CloudException {
            return try {
                when (throwable) {
                    is UnknownHostException -> {
                        CloudException(CODE_NO_NETWORK, throwable.message, throwable)
                    }
                    is InterruptedIOException -> {
                        CloudException(CODE_INTERRUPTED_IO, throwable.message, throwable)
                    }
                    is HttpException -> {
                        CloudException(CODE_NO_HTTP, throwable.message, throwable)
                    }
                    is CloudException -> {
                        when (throwable.code) {
                            CODE_TOKEN_INVALID -> {//token失效
                                CloudException(CODE_TOKEN_INVALID, throwable.message, throwable)
                            }

                            else -> {
                                throwable
                            }
                        }
                    }
                    else -> {
                        CloudException(CODE_UNKNOWN, throwable.message ?: "", throwable)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                CloudException(CODE_UNKNOWN, e.message ?: "", throwable)
            }
        }
    }
}
